package org.bot.server.config;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 沧月
 * @Date: 2023/12/9 20:51
 * @Description: 登录管理
 */
public class LoginCache {

    private static final int EXPIRATION_TIME_MINUTES = 30; // 过期时间为30分钟
    private static final Map<String, LocalDateTime> loginMap = new HashMap<>();

    static {
        // 启动定时任务，每隔一段时间清理过期数据
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(LoginCache::cleanExpiredData, 0, 1, TimeUnit.HOURS);
    }

    public static void addLogin(String token) {
        loginMap.put(token, LocalDateTime.now().plusMinutes(EXPIRATION_TIME_MINUTES));
    }

    public static boolean isLoginValid(String token) {
        if (token == null){
            return false;
        }
        LocalDateTime expirationTime = loginMap.get(token);
        boolean stat = expirationTime != null && expirationTime.isAfter(LocalDateTime.now());
        if (stat) {
            addLogin(token);
        }
        return stat;
    }

    private static void cleanExpiredData() {
        LocalDateTime now = LocalDateTime.now();
        // 清理过期数据
        loginMap.entrySet().removeIf(entry -> entry.getValue().isBefore(now));
    }

}
